<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="数据结构与算法," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="一、什么是赫夫曼编码 哈夫曼编码(Huffman Coding)，又称霍夫曼编码，是一种编码方式，可变字长编码(VLC)的一种。Huffman于1952年提出一种编码方法，该方法完全依据字符出现概率来构造异字头的平均长度最短的码字，有时称之为最佳编码， 使用赫夫曼编码可以有效的压缩数据，通常可以节省20%~90%的空间。 在理解赫夫曼编码前，我们需要对通讯领域的两种编码方式有个粗略的了解。">
<meta property="og:type" content="article">
<meta property="og:title" content="数据结构与算法（十四）：赫夫曼编码">
<meta property="og:url" content="http://blog.xiajibagao.top/2020/07/19/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E5%8D%81%E5%9B%9B%EF%BC%89%EF%BC%9A%E8%B5%AB%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="一、什么是赫夫曼编码 哈夫曼编码(Huffman Coding)，又称霍夫曼编码，是一种编码方式，可变字长编码(VLC)的一种。Huffman于1952年提出一种编码方法，该方法完全依据字符出现概率来构造异字头的平均长度最短的码字，有时称之为最佳编码， 使用赫夫曼编码可以有效的压缩数据，通常可以节省20%~90%的空间。 在理解赫夫曼编码前，我们需要对通讯领域的两种编码方式有个粗略的了解。">
<meta property="og:locale">
<meta property="og:image" content="http://img.xiajibagao.top/编码转树.png">
<meta property="article:published_time" content="2020-07-18T16:00:00.000Z">
<meta property="article:modified_time" content="2020-10-27T02:07:02.224Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="数据结构与算法">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.xiajibagao.top/编码转树.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2020/07/19/数据结构/数据结构与算法（十四）：赫夫曼编码/"/>





  <title>数据结构与算法（十四）：赫夫曼编码 | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2020/07/19/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E5%8D%81%E5%9B%9B%EF%BC%89%EF%BC%9A%E8%B5%AB%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">数据结构与算法（十四）：赫夫曼编码</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-19T00:00:00+08:00">
                2020-07-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" itemprop="url" rel="index">
                    <span itemprop="name">数据结构与算法</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.5k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="一-什么是赫夫曼编码">一、什么是赫夫曼编码</h2>
<p>哈夫曼编码(Huffman Coding)，又称霍夫曼编码，是一种编码方式，可变字长编码(VLC)的一种。Huffman于1952年提出一种编码方法，该方法完全依据字符出现概率来构造异字头的平均长度最短的码字，有时称之为最佳编码，</p>
<p>使用赫夫曼编码可以有效的压缩数据，通常可以节省20%~90%的空间。</p>
<p>在理解赫夫曼编码前，我们需要对通讯领域的两种编码方式有个粗略的了解。</p>
<p>假设我们需要传输 <code>I'm a jvav programmer and I love programming</code>这样一句话，我们有两种传输方式：</p>
<ol type="1">
<li><p>定长编码</p>
<p>直接转换为对应长度的二进制格式</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">01101111</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100111</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100111</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span> <span class="number">00100000</span></span><br></pre></td></tr></table></figure>
<p>总长度为296个字符</p></li>
<li><p>变长编码</p>
<p>按照各个字符出现的次数进行编码，按出现次数编码，出现次数越多的，则编码越小：</p>
<p>比如空格出现最多次，然后是a，以此类推......</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">0</span>=  ，<span class="number">1</span>=a，<span class="number">10</span>=i，<span class="number">11</span>=o......</span><br></pre></td></tr></table></figure>
<p>当传输的信息越多的时候，变长编码实际传输的长度相对定长编码就越小</p></li>
</ol>
<p>另外，我们还需要了解一下什么是补码：</p>
<blockquote>
<p>计算机里面只有加法器，没有减法器，所以减法必须用加法来完成。 对于 100 以内的十进制数，“-1”就可以用"+99"代替。比如 25 － 1 ＝ 24，可以写成 25 ＋ 99 ＝ (1)24。 如果限定了两位数，那“-1”和“+99”就是等效的。同样，“-2”可以用“+98”代替。</p>
<p>它们之间，称为<strong>补数</strong>，而100就称为<strong>模</strong>。</p>
<p>对于<strong>8位二进制数</strong>：0000 0000~1111 1111(255)，<strong>模为256</strong>。 －1，可以用 +255(1111 1111)代替。 －2，可以用 +254(1111 1110)代替</p>
<p>这些二进制数，就称为负数的<strong>补码</strong></p>
</blockquote>
<h2 id="二-赫夫曼编码思路">二、赫夫曼编码思路</h2>
<p>同样举个例子，我们要传输 <code>i like like like java do you like a java</code>这段话</p>
<ol type="1">
<li><p>统计各字符的出现次数</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">d:<span class="number">1</span> y:<span class="number">1</span> u:<span class="number">1</span> j:<span class="number">2</span> v:<span class="number">2</span> o:<span class="number">2</span> l:<span class="number">4</span> k:<span class="number">4</span> e:<span class="number">4</span> i:<span class="number">5</span> a:<span class="number">5</span> :<span class="number">9</span></span><br></pre></td></tr></table></figure></li>
<li><p>将字符出现次数作为节点的权，构建一个赫夫曼树（这里步骤同<a target="_blank" rel="noopener" href="https://www.cnblogs.com/Createsequence/p/13331722.html#_label1">上一篇文章</a>）</p>
<figure>
<img src="http://img.xiajibagao.top/编码转树.png" alt="image-20200717213740072"><figcaption aria-hidden="true">image-20200717213740072</figcaption>
</figure></li>
<li><p>我们使用0和1来描述某个节点在树中往左或往右的路径，比如j，从根节点出发抵达j的路径就是0000，抵达i的路径就是101</p>
<p>于是现在对所有字符的路径进行统计，就有：</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">o: <span class="number">1000</span>     u: <span class="number">10010</span>     d: <span class="number">100110</span>     y: <span class="number">100111</span>    i: <span class="number">101</span>    a : <span class="number">110</span></span><br><span class="line">k: <span class="number">1110</span>     e: <span class="number">1111</span>      j: <span class="number">0000</span>       v: <span class="number">0001</span>      l: <span class="number">001</span>      : <span class="number">01</span></span><br></pre></td></tr></table></figure></li>
<li><p>按照上面的路径，我们将其转为二进制</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1010100110111101111010011011110111101001101111011110100001100001110011001111000011001111000100100100110111101111011100100001100001110</span></span><br></pre></td></tr></table></figure>
<p>直接转为二进制长度为359，而经过赫夫曼编码长度则是133，与直接转为二进制相比，缩短了62.9%</p></li>
</ol>
<h2 id="三-代码实现">三、代码实现</h2>
<h3 id="1创建节点类">1.创建节点类</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>：CreateSequence</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>：2020-07-18 13:28</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>：赫夫曼编码用节点</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HuffmanCodeNode</span> <span class="keyword">implements</span> <span class="title">Comparable</span>&lt;<span class="title">HuffmanCodeNode</span>&gt;</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//字符</span></span><br><span class="line">    Byte data;</span><br><span class="line">    <span class="comment">//权值</span></span><br><span class="line">    <span class="keyword">int</span> weight;</span><br><span class="line">    HuffmanCodeNode left;</span><br><span class="line">    HuffmanCodeNode right;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">HuffmanCodeNode</span><span class="params">(Byte data, <span class="keyword">int</span> weight)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.data = data;</span><br><span class="line">        <span class="keyword">this</span>.weight = weight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">HuffmanCodeNode</span><span class="params">(HuffmanCodeNode left, HuffmanCodeNode right)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//计算子节点权值之和</span></span><br><span class="line">        <span class="keyword">this</span>.weight = left.weight + right.weight;</span><br><span class="line">        <span class="keyword">this</span>.left = left;</span><br><span class="line">        <span class="keyword">this</span>.right = right;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compareTo</span><span class="params">(HuffmanCodeNode o)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//从小到大排序</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.weight - o.weight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;&#123;&quot;</span> +</span><br><span class="line">            <span class="string">&quot;data=&quot;</span> + data +</span><br><span class="line">            <span class="string">&quot;, weight=&quot;</span> + weight +</span><br><span class="line">            <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2统计字符出现次数并组装节点列表">2.统计字符出现次数，并组装节点列表</h3>
<p>对应思路中的第一步：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 统计字符在字符串中的出现次数，并组装节点列表</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> str 字符串</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> List&lt;HuffmanCodeNode&gt; <span class="title">getNodes</span><span class="params">(String str)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//将字符串转为字符串数组</span></span><br><span class="line">    <span class="keyword">byte</span>[] strBytes = str.getBytes();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//遍历字节数组，并且统计某一字符出现次数</span></span><br><span class="line">    Map&lt;Byte, Integer&gt; counts = <span class="keyword">new</span> HashMap&lt;&gt;(<span class="number">24</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">byte</span> b : bytes) &#123;</span><br><span class="line">        Integer count = counts.get(b);</span><br><span class="line">        <span class="comment">//判断某一字符是否第一次出现</span></span><br><span class="line">        <span class="keyword">if</span> (count == <span class="keyword">null</span>) &#123;</span><br><span class="line">            counts.put(b, <span class="number">1</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//不是就让出现次数+1</span></span><br><span class="line">            counts.put(b, count ++);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//将map转为节点集合</span></span><br><span class="line">    List&lt;HuffmanCodeNode&gt; nodes = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">for</span> (Map.Entry&lt;Byte, Integer&gt; entry : counts.entrySet()) &#123;</span><br><span class="line">        nodes.add(<span class="keyword">new</span> HuffmanCodeNode(entry.getKey(), entry.getValue()));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> nodes;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3生成赫夫曼树">3.生成赫夫曼树</h3>
<p>对应思路中的第二步：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 构建赫夫曼树</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> nodes 节点集合</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> 最终生成的树的根节点</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> HuffmanCodeNode <span class="title">createTree</span><span class="params">(List&lt;HuffmanCodeNode&gt; nodes)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//构建树</span></span><br><span class="line">    <span class="keyword">while</span> (nodes.size() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="comment">//从小到大排序</span></span><br><span class="line">        Collections.sort(nodes);</span><br><span class="line">        <span class="comment">//取出最小的两个数构建树</span></span><br><span class="line">        HuffmanCodeNode left = nodes.get(<span class="number">0</span>);</span><br><span class="line">        HuffmanCodeNode right = nodes.get(<span class="number">1</span>);</span><br><span class="line">        HuffmanCodeNode parant = <span class="keyword">new</span> HuffmanCodeNode(left, right);</span><br><span class="line">        <span class="comment">//删除两个节点</span></span><br><span class="line">        nodes.remove(left);</span><br><span class="line">        nodes.remove(right);</span><br><span class="line">        <span class="comment">//将根节点添加至集合</span></span><br><span class="line">        nodes.add(parant);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//返回树的根节点</span></span><br><span class="line">    <span class="keyword">return</span> nodes.get(<span class="number">0</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当然，这个时候可以通过前序遍历来检查是否构建成功</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 前序遍历</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> node 树的根节点</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">preOrder</span><span class="params">(HuffmanCodeNode node)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//递归</span></span><br><span class="line">    System.out.println(node.toString());</span><br><span class="line">    <span class="keyword">if</span> (node.left != <span class="keyword">null</span>) &#123;</span><br><span class="line">        preOrder(node.left);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (node.right != <span class="keyword">null</span>) &#123;</span><br><span class="line">        preOrder(node.right);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4得到赫夫曼编码">4.得到赫夫曼编码</h3>
<p>对应思路中的第三步：</p>
<p>我们已经得到了赫夫曼树，现在我们需要获得从根节点到各个叶子结点的路径，也就是赫夫曼编码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 生成赫夫曼树对应的赫夫曼编码集合</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> Map&lt;Byte, String&gt; huffmanCodes = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 储存某个叶子节点的拼接路径</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder();</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将传入的节点作为树的根节点，找到其所有的叶子结点的赫夫曼编码，并放入赫夫曼编码集合</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> node 节点</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> way 叶子结点的路径，左为0，右为1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> builder 用于拼接路径</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> Map&lt;Byte, String&gt; <span class="title">getCodes</span><span class="params">(HuffmanCodeNode node, String way, StringBuilder builder)</span> </span>&#123;</span><br><span class="line">    StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder(builder);</span><br><span class="line">    <span class="comment">//建路径拼接至上一路径</span></span><br><span class="line">    stringBuilder.append(way);</span><br><span class="line">    <span class="keyword">if</span> (node != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">//判断当前是否为叶子节点</span></span><br><span class="line">        <span class="keyword">if</span> (node.data == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">//向左右递归直到找到叶子结点</span></span><br><span class="line">            getCodes(node.left, <span class="string">&quot;0&quot;</span>, stringBuilder);</span><br><span class="line">            getCodes(node.right, <span class="string">&quot;1&quot;</span>, stringBuilder);</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//已经是叶子结点，将路径存入集合</span></span><br><span class="line">            huffmanCodes.put(node.data, stringBuilder.toString());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> huffmanCodes;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> Map&lt;Byte, String&gt; <span class="title">getCodes</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//构建赫夫曼树</span></span><br><span class="line">    HuffmanCodeNode root = createTree();</span><br><span class="line">    <span class="comment">//处理左右子树</span></span><br><span class="line">    getCodes(root.left, <span class="string">&quot;0&quot;</span>, stringBuilder);</span><br><span class="line">    getCodes(root.right, <span class="string">&quot;1&quot;</span>, stringBuilder);</span><br><span class="line">    <span class="comment">//返回赫夫曼编码</span></span><br><span class="line">    <span class="keyword">return</span> huffmanCodes;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="5将得到的赫夫曼编码转回字节数组">5.将得到的赫夫曼编码转回字节数组</h3>
<p>对应思路中的第四步，也就是最后一步：</p>
<p>我们得到了赫夫曼编码表，也就是这玩意： <code>Map&lt;Byte, String&gt; huffmanCodes</code>，每串赫夫曼编码字符串都<strong>对应一个字符</strong>，我们需要<strong>处理赫夫曼编码的每一个字符</strong>，将其<strong>转为二进制后再转为byte</strong>，最后处理完得到一队字节数组。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将字符串对应的byte数组，转换为经过赫夫曼编码压缩后的byte数组</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> bytes</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> huffmanCodes</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">byte</span>[] zip(<span class="keyword">byte</span>[] bytes, Map&lt;Byte, String&gt; huffmanCodes) &#123;</span><br><span class="line">    <span class="comment">//获取赫夫曼编码</span></span><br><span class="line">    StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    <span class="comment">//遍历byte数组，一个byte表示一个字符</span></span><br><span class="line">    <span class="keyword">for</span> (Byte b : bytes) &#123;</span><br><span class="line">        <span class="comment">//将字符转为赫夫曼编码格式，一个字符对应8位编码</span></span><br><span class="line">        stringBuilder.append(huffmanCodes.get(b));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//一个字符对应对应的8位的赫夫曼编码，如果赫夫曼编码无法被8整除，就直接补齐赫夫曼编码不足八位的那一个字符</span></span><br><span class="line">    <span class="keyword">int</span> len = stringBuilder.length() % <span class="number">8</span> == <span class="number">0</span> ? stringBuilder.length() / <span class="number">8</span> : stringBuilder.length() / <span class="number">8</span> + <span class="number">1</span>;</span><br><span class="line">    <span class="comment">//System.out.println(&quot;有几个字符：&quot;+len);</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//将压缩后的赫夫曼编码按字符分开存储</span></span><br><span class="line">    <span class="keyword">byte</span>[] huffmanCodeBytes = <span class="keyword">new</span> <span class="keyword">byte</span>[len];</span><br><span class="line">    <span class="comment">//计录已处理几个字符</span></span><br><span class="line">    <span class="keyword">int</span> index = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">//每8位编码对应一个byte，所以步长为8</span></span><br><span class="line">    <span class="comment">//每循环一次处理一个byte，也就是一个字符</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; stringBuilder.length(); i += <span class="number">8</span>) &#123;</span><br><span class="line">        String strBytes;</span><br><span class="line">        <span class="comment">//判断编码长度是否超过8位</span></span><br><span class="line">        <span class="keyword">if</span> (i + <span class="number">8</span> &lt; stringBuilder.length()) &#123;</span><br><span class="line">            <span class="comment">//超过8位就从赫夫曼编码截取八位（也就是一个字符）</span></span><br><span class="line">            strBytes = stringBuilder.substring(i, i + <span class="number">8</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//否则就有多少截多少</span></span><br><span class="line">            strBytes = stringBuilder.substring(i);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//将赫夫曼编码转为二进制，存入byte数组</span></span><br><span class="line">        huffmanCodeBytes[index] = (<span class="keyword">byte</span>) Integer.parseInt(strBytes, <span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//位已处理字符数+1</span></span><br><span class="line">        index++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//循环结束后，返回赫夫曼编码按字符转换得到的字节数组</span></span><br><span class="line">    <span class="keyword">return</span> huffmanCodeBytes;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">byte</span>[] zip() &#123;</span><br><span class="line">    <span class="keyword">byte</span>[] bytes = str.getBytes();</span><br><span class="line">    Map&lt;Byte, String&gt; huffmanCodes = getCodes();</span><br><span class="line">    <span class="keyword">return</span> zip(bytes, huffmanCodes);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="6解码">6.解码</h3>
<p>信息被赫夫曼编码处理后我们会得到一队字节数组，如果要解码，我们需要先把字节数组按字符一个字节一个字节的转为二进制，然后通过赫夫曼编码表把二进制和字符字节一一找出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将byte转成二进制字符串</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> isComple 是否需要补高位。最后一个字节无需补位</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> b 要转换的字节</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> String <span class="title">byteToString</span><span class="params">(<span class="keyword">boolean</span> isComplate, <span class="keyword">byte</span> b)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> temp = b;</span><br><span class="line">    <span class="comment">//判断是否需要补齐高位</span></span><br><span class="line">    <span class="keyword">if</span> (isComplate) &#123;</span><br><span class="line">        temp |= <span class="number">256</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//返回temp对应的二进制补码</span></span><br><span class="line">    String str = Integer.toBinaryString(temp);</span><br><span class="line">    <span class="keyword">return</span> isComplate ? str.substring(str.length() - <span class="number">8</span>) : str;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 解码</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> huffmanCodes 赫夫曼编码表</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> huffmanBytes 赫夫曼编码处理过的字节数组</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> 原来未被转为赫夫曼编码的的字符串字节素组</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">byte</span>[] decode(Map&lt;Byte, String&gt; huffmanCodes, <span class="keyword">byte</span>[] huffmanBytes) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//将赫夫曼编码处理过byte数组转为二进制字符串</span></span><br><span class="line">    StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; huffmanBytes.length; i++) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">boolean</span> isComplate = <span class="keyword">true</span>;</span><br><span class="line">        <span class="comment">//如果是最后一个字节就不用补高位了</span></span><br><span class="line">        <span class="keyword">if</span> (i == huffmanBytes.length - <span class="number">1</span>) &#123;</span><br><span class="line">            isComplate = <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//拼接字节转的二进制字符串</span></span><br><span class="line">        stringBuilder.append(byteToString(isComplate, huffmanBytes[i]));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//把字符串按照指定赫夫曼编码进行解码</span></span><br><span class="line">    <span class="comment">//原本赫夫曼编码表是&lt;字节，二进制字符串&gt;，现在要转为&lt;二进制字符串，字节&gt;以通过转换得到的二进制字符串取出对应的字节</span></span><br><span class="line">    Map&lt;String, Byte&gt; reHuffmanCodes = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="keyword">for</span> (Map.Entry&lt;Byte, String&gt; entry : huffmanCodes.entrySet()) &#123;</span><br><span class="line">        reHuffmanCodes.put(entry.getValue(), entry.getKey());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    List&lt;Byte&gt; bytes = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="comment">//由于无法确认拼接后的二进制字符串每八位一定就能和某个字节对应，所以需要进行字符串匹配</span></span><br><span class="line">    <span class="comment">//这里可以简单理解为双指针，一号指针从i开始，二号指针从i+1开始</span></span><br><span class="line">    <span class="comment">//一号指针先指向字符串第i字符，然后二号指针从i+1个字符开始不断后移，然后进行进行匹配</span></span><br><span class="line">    <span class="comment">//比如：i=0，j=1，第一次截取并匹配的字符就是[0,1),也就是0；第二次是[0,2)，也就是01；然后是[0,3).....以此类推</span></span><br><span class="line">    <span class="comment">//直到找到以后，比如[2,7)，就移动一号指针到7，二号指针移动到8</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>, j = <span class="number">1</span>; i &lt; stringBuilder.length(); i = --j) &#123;</span><br><span class="line">        String key = <span class="string">&quot;&quot;</span>;</span><br><span class="line">        <span class="keyword">while</span> (!reHuffmanCodes.containsKey(key)) &#123;</span><br><span class="line">            key = stringBuilder.substring(i, j);</span><br><span class="line">            j++;</span><br><span class="line">        &#125;</span><br><span class="line">        bytes.add(reHuffmanCodes.get(key));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//由集合转为字节数组</span></span><br><span class="line">    <span class="keyword">byte</span> b[] = <span class="keyword">new</span> <span class="keyword">byte</span>[bytes.size()];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; b.length; i++) &#123;</span><br><span class="line">        b[i] = bytes.get(i);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> b;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="四-完整代码">四、完整代码</h2>
<p>具体代码和测试用例可以去<a target="_blank" rel="noopener" href="https://github.com/Createsequence/data_structure">GitHub</a>上看，这里就放实现类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>：CreateSequence</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>：2020-07-18 13:26</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>：赫夫曼编码</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HuffmanCode</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String str;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getStr</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> str;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">HuffmanCode</span><span class="params">(String code)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (code.length() == <span class="number">0</span> || code == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">&quot;字符串必须有至少一个字符！&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.str = code;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 统计字符在字符串中的出现次数，并组装节点列表</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;HuffmanCodeNode&gt; <span class="title">getNodes</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//将字符串转为字符串数组</span></span><br><span class="line">        <span class="keyword">byte</span>[] bytes = str.getBytes();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//遍历字节数组，并且统计某一字符出现次数</span></span><br><span class="line">        Map&lt;Byte, Integer&gt; counts = <span class="keyword">new</span> HashMap&lt;&gt;(<span class="number">24</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">byte</span> b : bytes) &#123;</span><br><span class="line">            Integer count = counts.get(b);</span><br><span class="line">            <span class="comment">//判断某一字符是否第一次出现</span></span><br><span class="line">            <span class="keyword">if</span> (count == <span class="keyword">null</span>) &#123;</span><br><span class="line">                counts.put(b, <span class="number">1</span>);</span><br><span class="line">            &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//不是就让出现次数+1</span></span><br><span class="line">                counts.put(b, count ++);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//将map转为节点集合</span></span><br><span class="line">        List&lt;HuffmanCodeNode&gt; nodes = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (Map.Entry&lt;Byte, Integer&gt; entry : counts.entrySet()) &#123;</span><br><span class="line">            nodes.add(<span class="keyword">new</span> HuffmanCodeNode(entry.getKey(), entry.getValue()));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> nodes;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 构建赫夫曼树</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> nodes</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> HuffmanCodeNode <span class="title">createTree</span><span class="params">(List&lt;HuffmanCodeNode&gt; nodes)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//构建树</span></span><br><span class="line">        <span class="keyword">while</span> (nodes.size() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="comment">//从小到大排序</span></span><br><span class="line">            Collections.sort(nodes);</span><br><span class="line">            <span class="comment">//取出最小的两个数构建树</span></span><br><span class="line">            HuffmanCodeNode left = nodes.get(<span class="number">0</span>);</span><br><span class="line">            HuffmanCodeNode right = nodes.get(<span class="number">1</span>);</span><br><span class="line">            HuffmanCodeNode parant = <span class="keyword">new</span> HuffmanCodeNode(left, right);</span><br><span class="line">            <span class="comment">//删除两个节点</span></span><br><span class="line">            nodes.remove(left);</span><br><span class="line">            nodes.remove(right);</span><br><span class="line">            <span class="comment">//将根节点添加至集合</span></span><br><span class="line">            nodes.add(parant);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//返回树的根节点</span></span><br><span class="line">        <span class="keyword">return</span> nodes.get(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> HuffmanCodeNode <span class="title">createTree</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> createTree(getNodes());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 前序遍历</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> node 树的根节点</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">preOrder</span><span class="params">(HuffmanCodeNode node)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//递归</span></span><br><span class="line">        System.out.println(node.toString());</span><br><span class="line">        <span class="keyword">if</span> (node.left != <span class="keyword">null</span>) &#123;</span><br><span class="line">            preOrder(node.left);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (node.right != <span class="keyword">null</span>) &#123;</span><br><span class="line">            preOrder(node.right);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">preOrder</span><span class="params">()</span></span>&#123;</span><br><span class="line">        HuffmanCodeNode root = createTree(getNodes());</span><br><span class="line">        preOrder(root);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 生成赫夫曼树对应的赫夫曼编码集合</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> Map&lt;Byte, String&gt; huffmanCodes = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 储存某个叶子节点的拼接路径</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将传入的节点作为树的根节点，找到其所有的叶子结点的赫夫曼编码，并放入赫夫曼编码集合</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> node 节点</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> way 叶子结点的路径，左为0，右为1</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> builder 用于拼接路径</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> Map&lt;Byte, String&gt; <span class="title">getCodes</span><span class="params">(HuffmanCodeNode node, String way, StringBuilder builder)</span> </span>&#123;</span><br><span class="line">        StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder(builder);</span><br><span class="line">        <span class="comment">//建路径拼接至上一路径</span></span><br><span class="line">        stringBuilder.append(way);</span><br><span class="line">        <span class="keyword">if</span> (node != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">//判断当前是否为叶子节点</span></span><br><span class="line">            <span class="keyword">if</span> (node.data == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//向左右递归直到找到叶子结点</span></span><br><span class="line">                getCodes(node.left, <span class="string">&quot;0&quot;</span>, stringBuilder);</span><br><span class="line">                getCodes(node.right, <span class="string">&quot;1&quot;</span>, stringBuilder);</span><br><span class="line">            &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//已经是叶子结点，将路径存入集合</span></span><br><span class="line">                huffmanCodes.put(node.data, stringBuilder.toString());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//返回赫夫曼编码</span></span><br><span class="line">        <span class="keyword">return</span> huffmanCodes;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map&lt;Byte, String&gt; <span class="title">getCodes</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//构建赫夫曼树</span></span><br><span class="line">        HuffmanCodeNode root = createTree();</span><br><span class="line">        <span class="comment">//处理左右子树</span></span><br><span class="line">        getCodes(root.left, <span class="string">&quot;0&quot;</span>, stringBuilder);</span><br><span class="line">        getCodes(root.right, <span class="string">&quot;1&quot;</span>, stringBuilder);</span><br><span class="line">        <span class="comment">//返回赫夫曼编码</span></span><br><span class="line">        <span class="keyword">return</span> huffmanCodes;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将字符串对应的byte数组，转换为经过赫夫曼编码压缩后的byte数组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> bytes</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> huffmanCodes</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">byte</span>[] zip(<span class="keyword">byte</span>[] bytes, Map&lt;Byte, String&gt; huffmanCodes) &#123;</span><br><span class="line">        <span class="comment">//获取赫夫曼编码</span></span><br><span class="line">        StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">        <span class="comment">//遍历byte数组，一个byte表示一个字符</span></span><br><span class="line">        <span class="keyword">for</span> (Byte b : bytes) &#123;</span><br><span class="line">            <span class="comment">//将字符转为赫夫曼编码格式，一个字符对应8位编码</span></span><br><span class="line">            stringBuilder.append(huffmanCodes.get(b));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//一个字符对应对应的8位的赫夫曼编码，如果赫夫曼编码无法被8整除，就直接补齐赫夫曼编码不足八位的那一个字符</span></span><br><span class="line">        <span class="keyword">int</span> len = stringBuilder.length() % <span class="number">8</span> == <span class="number">0</span> ? stringBuilder.length() / <span class="number">8</span> : stringBuilder.length() / <span class="number">8</span> + <span class="number">1</span>;</span><br><span class="line">        <span class="comment">//System.out.println(&quot;有几个字符：&quot;+len);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//将压缩后的赫夫曼编码按字符分开存储</span></span><br><span class="line">        <span class="keyword">byte</span>[] huffmanCodeBytes = <span class="keyword">new</span> <span class="keyword">byte</span>[len];</span><br><span class="line">        <span class="comment">//计录已处理几个字符</span></span><br><span class="line">        <span class="keyword">int</span> index = <span class="number">0</span>;</span><br><span class="line">        <span class="comment">//每8位编码对应一个byte，所以步长为8</span></span><br><span class="line">        <span class="comment">//每循环一次处理一个byte，也就是一个字符</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; stringBuilder.length(); i += <span class="number">8</span>) &#123;</span><br><span class="line">            String strBytes;</span><br><span class="line">            <span class="comment">//判断编码长度是否超过8位</span></span><br><span class="line">            <span class="keyword">if</span> (i + <span class="number">8</span> &lt; stringBuilder.length()) &#123;</span><br><span class="line">                <span class="comment">//超过8位就从赫夫曼编码截取八位（也就是一个字符）</span></span><br><span class="line">                strBytes = stringBuilder.substring(i, i + <span class="number">8</span>);</span><br><span class="line">            &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//否则就有多少截多少</span></span><br><span class="line">                strBytes = stringBuilder.substring(i);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//将赫夫曼编码转为二进制，存入byte数组</span></span><br><span class="line">            huffmanCodeBytes[index] = (<span class="keyword">byte</span>) Integer.parseInt(strBytes, <span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//位已处理字符数+1</span></span><br><span class="line">            index++;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//循环结束后，返回赫夫曼编码按字符转换得到的字节数组</span></span><br><span class="line">        <span class="keyword">return</span> huffmanCodeBytes;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] zip() &#123;</span><br><span class="line">        <span class="keyword">byte</span>[] bytes = str.getBytes();</span><br><span class="line">        Map&lt;Byte, String&gt; huffmanCodes = getCodes();</span><br><span class="line">        <span class="keyword">return</span> zip(bytes, huffmanCodes);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将byte转成二进制字符串</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> isComple 是否需要补高位。最后一个字节无需补位</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> b 要转换的字节</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> String <span class="title">byteToString</span><span class="params">(<span class="keyword">boolean</span> isComplate, <span class="keyword">byte</span> b)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> temp = b;</span><br><span class="line">        <span class="comment">//判断是否需要补齐高位</span></span><br><span class="line">        <span class="keyword">if</span> (isComplate) &#123;</span><br><span class="line">            temp |= <span class="number">256</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//返回temp对应的二进制补码</span></span><br><span class="line">        String str = Integer.toBinaryString(temp);</span><br><span class="line">        <span class="keyword">return</span> isComplate ? str.substring(str.length() - <span class="number">8</span>) : str;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 解码</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> huffmanCodes 赫夫曼编码表</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> huffmanBytes 赫夫曼编码处理过的字节数组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 原来未被转为赫夫曼编码的的字符串字节素组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">byte</span>[] decode(Map&lt;Byte, String&gt; huffmanCodes, <span class="keyword">byte</span>[] huffmanBytes) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//将赫夫曼编码处理过byte数组转为二进制字符串</span></span><br><span class="line">        StringBuilder stringBuilder = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; huffmanBytes.length; i++) &#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">boolean</span> isComplate = <span class="keyword">true</span>;</span><br><span class="line">            <span class="comment">//如果是最后一个字节就不用补高位了</span></span><br><span class="line">            <span class="keyword">if</span> (i == huffmanBytes.length - <span class="number">1</span>) &#123;</span><br><span class="line">                isComplate = <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//拼接字节转的二进制字符串</span></span><br><span class="line">            stringBuilder.append(byteToString(isComplate, huffmanBytes[i]));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//把字符串按照指定赫夫曼编码进行解码</span></span><br><span class="line">        <span class="comment">//原本赫夫曼编码表是&lt;字节，二进制字符串&gt;，现在要转为&lt;二进制字符串，字节&gt;以通过转换得到的二进制字符串取出对应的字节</span></span><br><span class="line">        Map&lt;String, Byte&gt; reHuffmanCodes = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (Map.Entry&lt;Byte, String&gt; entry : huffmanCodes.entrySet()) &#123;</span><br><span class="line">            reHuffmanCodes.put(entry.getValue(), entry.getKey());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        List&lt;Byte&gt; bytes = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="comment">//由于无法确认拼接后的二进制字符串每八位一定就能和某个字节对应，所以需要进行字符串匹配</span></span><br><span class="line">        <span class="comment">//这里可以简单理解为双指针，一号指针从i开始，二号指针从i+1开始</span></span><br><span class="line">        <span class="comment">//一号指针先指向字符串第i字符，然后二号指针从i+1个字符开始不断后移，然后进行进行匹配</span></span><br><span class="line">        <span class="comment">//比如：i=0，j=1，第一次截取并匹配的字符就是[0,1),也就是0；第二次是[0,2)，也就是01；然后是[0,3).....以此类推</span></span><br><span class="line">        <span class="comment">//直到找到以后，比如[2,7)，就移动一号指针到7，二号指针移动到8</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>, j = <span class="number">1</span>; i &lt; stringBuilder.length(); i = --j) &#123;</span><br><span class="line">            String key = <span class="string">&quot;&quot;</span>;</span><br><span class="line">            <span class="keyword">while</span> (!reHuffmanCodes.containsKey(key)) &#123;</span><br><span class="line">                key = stringBuilder.substring(i, j);</span><br><span class="line">                j++;</span><br><span class="line">            &#125;</span><br><span class="line">            bytes.add(reHuffmanCodes.get(key));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//由集合转为字节数组</span></span><br><span class="line">        <span class="keyword">byte</span> b[] = <span class="keyword">new</span> <span class="keyword">byte</span>[bytes.size()];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; b.length; i++) &#123;</span><br><span class="line">            b[i] = bytes.get(i);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> b;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] decode(<span class="keyword">byte</span>[] huffmanBytes) &#123;</span><br><span class="line">        <span class="keyword">return</span> decode(huffmanCodes, huffmanBytes);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" rel="tag"># 数据结构与算法</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/17/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E5%8D%81%E4%B8%89%EF%BC%89%EF%BC%9A%E8%B5%AB%E5%A4%AB%E6%9B%BC%E6%A0%91/" rel="next" title="数据结构与算法（十三）：赫夫曼树">
                <i class="fa fa-chevron-left"></i> 数据结构与算法（十三）：赫夫曼树
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/07/20/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E5%8D%81%E4%BA%94%EF%BC%89%EF%BC%9A%E4%BA%8C%E5%8F%89%E6%8E%92%E5%BA%8F%E6%A0%91/" rel="prev" title="数据结构与算法（十五）：二叉排序树">
                数据结构与算法（十五）：二叉排序树 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-%E4%BB%80%E4%B9%88%E6%98%AF%E8%B5%AB%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81"><span class="nav-text">一、什么是赫夫曼编码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-%E8%B5%AB%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81%E6%80%9D%E8%B7%AF"><span class="nav-text">二、赫夫曼编码思路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="nav-text">三、代码实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E5%88%9B%E5%BB%BA%E8%8A%82%E7%82%B9%E7%B1%BB"><span class="nav-text">1.创建节点类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E7%BB%9F%E8%AE%A1%E5%AD%97%E7%AC%A6%E5%87%BA%E7%8E%B0%E6%AC%A1%E6%95%B0%E5%B9%B6%E7%BB%84%E8%A3%85%E8%8A%82%E7%82%B9%E5%88%97%E8%A1%A8"><span class="nav-text">2.统计字符出现次数，并组装节点列表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E7%94%9F%E6%88%90%E8%B5%AB%E5%A4%AB%E6%9B%BC%E6%A0%91"><span class="nav-text">3.生成赫夫曼树</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E5%BE%97%E5%88%B0%E8%B5%AB%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81"><span class="nav-text">4.得到赫夫曼编码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5%E5%B0%86%E5%BE%97%E5%88%B0%E7%9A%84%E8%B5%AB%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81%E8%BD%AC%E5%9B%9E%E5%AD%97%E8%8A%82%E6%95%B0%E7%BB%84"><span class="nav-text">5.将得到的赫夫曼编码转回字节数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6%E8%A7%A3%E7%A0%81"><span class="nav-text">6.解码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B-%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81"><span class="nav-text">四、完整代码</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
